package com.ktjiaoyu.crm.controller;

import com.ktjiaoyu.crm.pojo.Right;
import com.ktjiaoyu.crm.pojo.User;
import com.ktjiaoyu.crm.realm.MyShiroRealm;
import com.ktjiaoyu.crm.service.RightService;
import com.ktjiaoyu.crm.service.UserService;
import com.ktjiaoyu.crm.util.CipherUtil;
import com.ktjiaoyu.crm.util.RedisTemplateUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @ClassName : LoginController
 * @Description :
 * @Author : Lzz
 * @Date: 2023/11/22 08:45:48
 */
@Controller
public class LoginController {

    @Resource
    UserService userService;

    private String SHIRO_LOGIN_COUNT = "shiro_login_count:";

    @Resource
    private RedisTemplateUtil redisTemplateUtil;

    @Resource
    private RightService rightService;

    @RequestMapping("/toLogin")
    public String toLogin(){

        return "login";
    }

    @RequestMapping(value = "/login")
    public String login(String usrName, String usrPassword, Model model, HttpSession session){
        try {
            //1、构建token
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(usrName, usrPassword);
            //2、调用Subject.login()登录方法
            Subject subject = SecurityUtils.getSubject();
            subject.login(usernamePasswordToken);
            //登录成功之后，将用户信息存入session
            User user = (User) subject.getPrincipal();
            session.setAttribute("loginUser",user);
            //根据当前登录用户的角色ID查询角色对应的权限列表
            List<Right> rightList = rightService.getRightsByRoleId(user.getUsrRoleId());
            session.setAttribute("rights", rightList);
            //登录成功，清除Redis登录计数
            redisTemplateUtil.del(SHIRO_LOGIN_COUNT+usrName);
            //清空当前用户权限缓存
            RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
            MyShiroRealm realm = (MyShiroRealm) rsm.getRealms().iterator().next();
            realm.clearMyCachedAuthorizationInfo();
        } catch (UnknownAccountException | IncorrectCredentialsException e){
            model.addAttribute("msg","用户名或密码错误，登录失败！ ");
            return "forward:/toLogin";
        } catch (LockedAccountException e){
            model.addAttribute("msg","用户被禁用，登录失败！ ");
            return "forward:/toLogin";
        } catch (DisabledAccountException ex){
            model.addAttribute("msg","用户密码输入错误超过5次，账号被锁定，请一小时后再重试！ ");
            return "forward:/toLogin";
        } catch (AuthenticationException e){
            model.addAttribute("msg","认证异常，登录失败！ ");
            return "forward:/toLogin";
        } catch (Exception e) {
            model.addAttribute("msg","系统出现其他异常！");
            e.printStackTrace();
            return "forward:/toLogin";
        }
        return "main";
    }

    @RequestMapping(value = "/logout")
    public String logout(HttpSession session){
        //调用shiro的logout()退出登录
        SecurityUtils.getSubject().logout();
        return "login";
    }

    @RequestMapping("/403")
    public String to403(){

        return "403";
    }

}
